{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Isi Penting Generator: Product Description Style"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Generate a long text output with the style of a product description when given important facts (isi penting in Malay)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "\n",
    "This tutorial is available as an IPython notebook at [Malaya/example/isi-penting-generator-product-description-style](https://github.com/huseinzol05/Malaya/tree/master/example/isi-penting-generator-product-description-style).\n",
    "    \n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-warning\">\n",
    "\n",
    "The results you see here are generated using stochastic methods. Learn more about the stochastic process on <a href=\"https://en.wikipedia.org/wiki/Stochastic_process\" target=\"_blank\">Wikipedia</a>\n",
    "    \n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 3.13 s, sys: 269 ms, total: 3.4 s\n",
      "Wall time: 3.25 s\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/maguswyvern/PythonVenvs/dev-malaya/lib/python3.10/site-packages/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3397\n",
      "  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))\n",
      "/home/maguswyvern/PythonVenvs/dev-malaya/lib/python3.10/site-packages/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3927\n",
      "  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "import malaya\n",
    "from pprint import pprint"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### List all available HuggingFace transformers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `malaya` library has a built in function to find all available transformers for this task. As of writing we have two transformers which are:\n",
    "\n",
    "1. mesolitica/finetune-isi-penting-generator-t5-base-standard-bahasa-cased <br>\n",
    "https://huggingface.co/mesolitica/finetune-isi-penting-generator-t5-base-standard-bahasa-cased\n",
    "   \n",
    "2. mesolitica/finetune-isi-penting-generator-t5-small-standard-bahasa-cased <br>\n",
    "https://huggingface.co/mesolitica/finetune-isi-penting-generator-t5-small-standard-bahasa-cased"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'mesolitica/finetune-isi-penting-generator-t5-small-standard-bahasa-cased': {'Size (MB)': 242,\n",
       "  'ROUGE-1': 0.24620333,\n",
       "  'ROUGE-2': 0.05896076,\n",
       "  'ROUGE-L': 0.15158954,\n",
       "  'Suggested length': 1024},\n",
       " 'mesolitica/finetune-isi-penting-generator-t5-base-standard-bahasa-cased': {'Size (MB)': 892,\n",
       "  'ROUGE-1': 0.24620333,\n",
       "  'ROUGE-2': 0.05896076,\n",
       "  'ROUGE-L': 0.15158954,\n",
       "  'Suggested length': 1024}}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "malaya.generator.isi_penting.available_huggingface"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load HuggingFace\n",
    "\n",
    "The Generator transformer in `malaya` is quite unique, most of the text generative model we found on the internet like GPT2 or Markov simply just continue the prefix input from user, but not for our Generator transformer. \n",
    "\n",
    "We want to generate an article or karangan like high school when the users give 'isi penting' or important facts for the article."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "def huggingface(\n",
    "    model: str = 'mesolitica/finetune-isi-penting-generator-t5-base-standard-bahasa-cased',\n",
    "    force_check: bool = True,\n",
    "    **kwargs,\n",
    "):\n",
    "    \"\"\"\n",
    "    Load HuggingFace model to generate text based on isi penting.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    model: str, optional (default='mesolitica/finetune-isi-penting-generator-t5-base-standard-bahasa-cased')\n",
    "        Check available models at `malaya.generator.isi_penting.available_huggingface`.\n",
    "    force_check: bool, optional (default=True)\n",
    "        Force check model one of malaya model.\n",
    "        Set to False if you have your own huggingface model.\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: malaya.torch_model.huggingface.IsiPentingGenerator\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "You are using the default legacy behaviour of the <class 'transformers.models.t5.tokenization_t5.T5Tokenizer'>. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565\n"
     ]
    }
   ],
   "source": [
    "model = malaya.generator.isi_penting.huggingface()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is the `generate` function and the parameters it expects. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "def generate(\n",
    "    self,\n",
    "    strings: List[str],\n",
    "    mode: str = 'surat-khabar',\n",
    "    **kwargs,\n",
    "):\n",
    "    \"\"\"\n",
    "    generate a long text given a isi penting.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    strings : List[str]\n",
    "    mode: str, optional (default='surat-khabar')\n",
    "        Mode supported. Allowed values:\n",
    "\n",
    "        * ``'surat-khabar'`` - news style writing.\n",
    "        * ``'tajuk-surat-khabar'`` - headline news style writing.\n",
    "        * ``'artikel'`` - article style writing.\n",
    "        * ``'penerangan-produk'`` - product description style writing.\n",
    "        * ``'karangan'`` - karangan sekolah style writing.\n",
    "\n",
    "    **kwargs: vector arguments pass to huggingface `generate` method.\n",
    "        Read more at https://huggingface.co/docs/transformers/main_classes/text_generation\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: List[str]\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Benefits of HuggingFace\n",
    "\n",
    "With the `generate` method you can use Greedy, Beam, Sampling, Nucleus decoder and so much more, read more about it on the [HuggingFace Article on How to Generate](https://huggingface.co/blog/how-to-generate). And recently, HuggingFace also released a new article [Introducing Csearch](https://huggingface.co/blog/introducing-csearch)\n",
    "\n",
    "Let's give a few lines of important facts or isi penting for the model to use to generate text."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "isi_penting = ['ayam yang sihat dan sejahtera', 'nasi ayam yang sedap dan lazat', 'kedai bernama Husein Nasi Ayam']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we'll use the `generate` method and pass in a few of the vector arguments mentioned in a previous linked article by HuggingFace."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Husein Nasi Ayam adalah untuk mereka yang berada di sekitar rumah atau '\n",
      " 'pejabat mereka dan mungkin menginginkan sesuatu yang istimewa. Ia juga boleh '\n",
      " 'digunakan sebagai pemanis. Di sini kami membuat nasi ayam yang sedap dan '\n",
      " 'lazat. Dengan ramuan yang sihat dan kenyal, ini adalah cara yang lazat untuk '\n",
      " 'memulakan hari anda. Kami telah mencipta rasa yang asli, tanpa biji-bijian, '\n",
      " 'bebas gluten, dan bebas biji-bijian. Terdapat sebilangan rasa di sini di '\n",
      " 'kedai kami, seperti nasi ayam, nasi ayam, nasi ayam, nasi putih, dan banyak '\n",
      " 'lagi. Kami juga telah membuat nasi yang lazat seperti itu di rumah mereka '\n",
      " 'sendiri. Tidak seperti banyak rasa yang enak, kami tidak mencampurkan resipi '\n",
      " 'dengan bahan-bahan Amerika. Kami hanya menggunakan bahan-bahan berkualiti '\n",
      " 'tinggi, seperti ayam yang sihat dan sejahtera, seperti tepung gandum dan '\n",
      " 'nasi, yang kami dapat. Setiap nasi kami terdapat dalam satu kantung dengan '\n",
      " 'penutup yang mudah dan selamat. Kami tahu bahawa kami mempunyai restoran '\n",
      " 'yang lebih baik daripada kedai bernama Husein Nasi Ayam untuk nasi ayam yang '\n",
      " 'sedap dan sedap. Kami mahu nasi ayam ini menjadi makanan sihat. Kami ingin '\n",
      " 'memberi pengguna rasa yang sihat yang mereka suka.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, mode = 'penerangan-produk',\n",
    "    do_sample=True, \n",
    "    max_length=256, \n",
    "    top_k=50, \n",
    "    top_p=0.95,))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Husein Nasi Ayam adalah nasi ayam yang lazat dan enak yang dibuat dengan '\n",
      " 'ayam yang sihat dan sejahtera. Dibungkus dengan nasi ayam yang sedap dan '\n",
      " 'lazat, nasi ayam Husein Nasi Ayam adalah sumber protein yang hebat, yang '\n",
      " 'sangat baik untuk anjing yang gemuk dan anak anjing yang tidak dapat menahan '\n",
      " 'diri dari makan makanan yang tidak sihat. Husein Nasi Ayam adalah sumber '\n",
      " 'protein yang hebat, yang sangat baik untuk anjing yang gemuk dan anak anjing '\n",
      " 'yang tidak dapat menahan dari makan makanan yang tidak sihat.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, mode = 'penerangan-produk',\n",
    "    do_sample=True, \n",
    "    max_length=256, \n",
    "    penalty_alpha=0.8, top_k=4,))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "isi_penting = ['sabun lembut untuk kulit anda', \n",
    "               'sabun bebas dari DNA babi',\n",
    "               '44 herba dipetik oleh ibu tunggal yang cantik lagi ayu',\n",
    "               'sabun bebas dari kes rasuah SPRM',]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Formula yang terbukti memberikan kelegaan yang kaya untuk kulit, terutama '\n",
      " 'yang sensitif terhadap DNA babi. Rumus bebas kimia dan boleh dicampurkan '\n",
      " 'dengan bahan-bahan semula jadi lain, sabun lembut untuk kulit anda juga '\n",
      " 'memberikan kelegaan yang kaya. Formula ini meluap-luap, melembutkan, lembut '\n",
      " 'dan melembapkan. • Pembersihan badan yang lebih cepat dan pembersihan kulit '\n",
      " 'yang lebih mudah • Penyahhidratan badan yang lebih cepat & banyak dengan '\n",
      " 'pengelupasan mudah • Formula kaya ini meluap-luap, melembutkan dan lembut '\n",
      " 'tanpa meninggalkan tanda-tanda pengelupasan & bull; Diselitkan dengan '\n",
      " 'vitamin E dan D dan vitamin C, sabun ini melembutkan dan melembapkan kulit, '\n",
      " 'terutama yang sensitif terhadap DNA babi. Shampoo yang enak membuat anda '\n",
      " 'tidak boleh kering dan segar, dengan 44 herba dipetik oleh ibu tunggal yang '\n",
      " 'cantik lagi ayu. Shampoo adalah sabun bebas dari kes rasuah SPRM, sabun '\n",
      " 'bebas untuk lelaki, sabun bebas untuk lelaki, sabun bebas untuk wanita, dan '\n",
      " 'sabun untuk kanak-kanak. Shampoo adalah alternatif']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, do_sample=True, mode = 'penerangan-produk',\n",
    "    max_length=256,\n",
    "    top_k=50, \n",
    "    top_p=0.95, ))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['\"Saya rasa sabun lembut untuk kulit anda. Saya suka sabun, dan ia sangat '\n",
      " 'berkesan, jadi anda boleh merasa seperti anda mempunyai sabun bebas yang '\n",
      " 'anda gemari.\" '\n",
      " '-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, mode = 'penerangan-produk',\n",
    "    do_sample=True, \n",
    "    max_length=256, \n",
    "    penalty_alpha=0.8, top_k=4,))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you give better isi penting, the results will be much better."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# https://ms.wikipedia.org/wiki/Burger_Ramly\n",
    "isi_penting = ['Penubuhan Makma Mikrobiologi',\n",
    "               'mengawal kualiti produk',\n",
    "               'memastikan produknya adalah suci',\n",
    "               'satu tempat penyelidikan dan pembangunan produk',\n",
    "              'peralatan teknologi tinggi']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Penubuhan Makma Mikrobiologi (MSC) adalah program penyelidikan yang inovatif '\n",
      " 'yang menghasilkan \"penubuhan organik\" yang membolehkan anda memantau '\n",
      " 'persekitaran yang lebih baik dan mewujudkan persekitaran yang lebih sihat '\n",
      " 'untuk produk organik yang anda tanam secara lestari. MSC tidak mengawal '\n",
      " 'kualiti produk yang dihasilkan dalam organisma mikrobiologi atau manusia '\n",
      " 'kerana mereka terus dihasilkan tanpa lesen dan lesen yang sah. MSC adalah '\n",
      " 'satu-satunya pengeluar di dunia yang memastikan produknya adalah suci dan '\n",
      " 'boleh dipercayai dan bebas dari peralatan teknologi tinggi. Ia adalah satu '\n",
      " 'tempat penyelidikan dan pembangunan produk yang diiktiraf oleh ISO 9001 '\n",
      " 'untuk membantu syarikat-syarikat dalam industri organik.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, do_sample=True, mode = 'penerangan-produk',\n",
    "    max_length=256,\n",
    "    top_k=50, \n",
    "    top_p=0.95, ))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Penubuhan Makma Mikrobiologi - Penubuhan Makma Mikrobiologi - Penubuhan '\n",
      " 'Makma Mikrobiologi - Penubuhan Makma Mikrobiologi - Digunakan sebagai satu '\n",
      " 'tempat penyelidikan dan pembangunan produk dan peralatan teknologi tinggi '\n",
      " 'untuk mengawal kualiti produk dan memastikan produknya adalah suci.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, mode = 'penerangan-produk',\n",
    "    do_sample=True, \n",
    "    max_length=256, \n",
    "    penalty_alpha=0.8, top_k=4,))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
